package com.distribution.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.common.core.page.TableDataInfo;
import com.distribution.common.exception.ServiceException;
import com.distribution.common.utils.DictUtils;
import com.distribution.common.utils.poi.ExcelUtil;
import com.distribution.system.domain.bo.CmccDaOrderExportBO;
import com.distribution.system.domain.bo.CmccDaOrderInternalExportBO;
import com.distribution.system.domain.converter.CmccDaOrderWebConverter;
import com.distribution.system.domain.dto.CmccDaOrderListDTO;
import com.distribution.system.domain.entity.CmccDaOrder;
import com.distribution.system.domain.entity.CmccDaUpChannelInfo;
import com.distribution.system.domain.req.CmccDaOrderListExportReq;
import com.distribution.system.domain.req.CmccDaOrderListReq;
import com.distribution.system.domain.req.ReqResult;
import com.distribution.system.domain.vo.OrderListCountVO;
import com.distribution.system.mapper.SysUserMapper;
import com.distribution.system.service.CmccDaSubordinateOrderService;
import com.distribution.system.service.CmccDaUpChannelInfoService;
import com.distribution.system.service.PlaceOrderOperationService;
import com.distribution.system.utils.convert.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 下级作业（订单 控制器）
 *
 * @author destinyhlp
 * @date 2023/6/3 22:02
 */
@RestController
@RequestMapping(value = "/cmccDaSubordinateOrder")
@Slf4j
public class CmccDaSubordinateOrderController extends BaseController {
    @Resource
    CmccDaSubordinateOrderService cmccDaSubordinateOrderService;
    @Resource
    CmccDaOrderWebConverter cmccDaOrderWebConverter;
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    CmccDaUpChannelInfoService cmccDaUpChannelInfoService;


    /**
     * 下级作业列表数据
     *
     * @param cmccDaOrderListReq 请求参数
     * @return 列表数据
     */
    @PostMapping("/listCmccDaSubordinateOrder")
    TableDataInfo listCmccDaSubordinateOrder(@RequestBody CmccDaOrderListReq cmccDaOrderListReq) {
        //System.out.println("cmccDaOrderListReq = " + cmccDaOrderListReq);
        CmccDaOrderListDTO cmccDaOrderListReqToDto = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        List<Long> userList = cmccDaSubordinateOrderService.getSubordinateUserIdList();
        cmccDaOrderListReqToDto.setUserIdList(userList);
        startPage();
        List<CmccDaOrder> cmccDaOrders = cmccDaSubordinateOrderService.listCmccDaSubordinateOrder(cmccDaOrderListReqToDto);
        return getDataTable(cmccDaOrders);
    }
    @PreAuthorize("@ss.hasAnyRoles('firstLevelAgent,secondLevelAgent,agencyOperation,operationSupervisor')")
    @PostMapping("/getOrderStatusCount")
    ReqResult getOrderStatusCount(@RequestBody CmccDaOrderListReq cmccDaOrderListReq) {
        CmccDaOrderListDTO cmccDaOrderListReqToDto = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        List<Long> userList = cmccDaSubordinateOrderService.getSubordinateUserIdList();
        cmccDaOrderListReqToDto.setUserIdList(userList);
        List<CmccDaOrder> cmccDaOrderList = cmccDaSubordinateOrderService.listCmccDaSubordinateOrder(cmccDaOrderListReqToDto);
        int failCount = (int) cmccDaOrderList.stream().filter(f -> "0".equals(f.getOrderStatus())).count();
        int unOrderCount = (int) cmccDaOrderList.stream().filter(f -> "1".equals(f.getOrderStatus())).count();
        int processCount = (int) cmccDaOrderList.stream().filter(f -> "2".equals(f.getOrderStatus())).count();
        int successCount = (int) cmccDaOrderList.stream().filter(f -> "3".equals(f.getOrderStatus())).count();
        OrderListCountVO orderListCountVO = new OrderListCountVO(cmccDaOrderList.size(), failCount, unOrderCount, processCount, successCount);
        return ReqResult.success(orderListCountVO);
    }


    /**
     * 订单管理页面 数据导出
     *
     * @param response                      response
     * @param cmccDaOrderListExportReq cmccDaOrderListReq
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmccDaOrderListExportReq cmccDaOrderListExportReq) {
        CmccDaOrderListDTO cmccDaOrderListReqToDto = cmccDaOrderWebConverter.cmccDaOrderListExportReqToDto(cmccDaOrderListExportReq);
        List<Long> userList = cmccDaSubordinateOrderService.getSubordinateUserIdList();
        cmccDaOrderListReqToDto.setUserIdList(userList);
        List<CmccDaOrder> cmccDaOrders = cmccDaSubordinateOrderService.listCmccDaSubordinateOrder(cmccDaOrderListReqToDto);
        Long userId = getUserId();
        //获取当前登录用户
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        if (sysUser.isOperationSupervisor() || sysUser.isAdmin() || sysUser.isAgentOperation()) {
            List<CmccDaOrderInternalExportBO> cmccDaOrderExportBOS = BeanUtils.copyBeanCollection(CmccDaOrderInternalExportBO.class, cmccDaOrders);
            cmccDaOrderExportBOS.forEach(f -> {
                String productStatus = f.getProductStatus() == null ? "-1" : f.getProductStatus();
                f.setProductStatusDesc(DictUtils.getDictLabel("order_product_status", productStatus));
            });
            ExcelUtil<CmccDaOrderInternalExportBO> util = new ExcelUtil<>(CmccDaOrderInternalExportBO.class);
            util.exportExcel(response, cmccDaOrderExportBOS, "订单数据");
        } else {
            List<CmccDaOrderExportBO> cmccDaOrderExportBOS = BeanUtils.copyBeanCollection(CmccDaOrderExportBO.class, cmccDaOrders);
            cmccDaOrderExportBOS.forEach(f -> {
                String productStatus = f.getProductStatus() == null ? "-1" : f.getProductStatus();
                f.setProductStatusDesc(DictUtils.getDictLabel("order_product_status", productStatus));
            });
            ExcelUtil<CmccDaOrderExportBO> util = new ExcelUtil<>(CmccDaOrderExportBO.class);
            util.exportExcel(response, cmccDaOrderExportBOS, "订单数据");
        }
    }

    @PostMapping("/importOrderToUpdate")
    public void importOrderToUpdate(MultipartFile file){
        ExcelUtil<CmccDaOrderInternalExportBO> excelUtil = new ExcelUtil<CmccDaOrderInternalExportBO>(CmccDaOrderInternalExportBO.class);
        try {
            List<CmccDaOrderInternalExportBO> cmccDaOrderInternalExportBOS = excelUtil.importExcel(file.getInputStream());
            Map<String, List<CmccDaOrderInternalExportBO>> orders = cmccDaOrderInternalExportBOS.stream()
                    .collect(Collectors.groupingBy(CmccDaOrderInternalExportBO::getBindChannelInfoName));
            for (Map.Entry<String, List<CmccDaOrderInternalExportBO>> orderEntry : orders.entrySet()) {
                // 根据三方渠道名查询三方渠道ID
                List<CmccDaUpChannelInfo> list = cmccDaUpChannelInfoService.list(new LambdaQueryWrapper<CmccDaUpChannelInfo>()
                        .eq(CmccDaUpChannelInfo::getChannelName, orderEntry.getKey()));
                if (list == null || list.isEmpty()){
                    throw new ServiceException("渠道错误");
                }
                CmccDaUpChannelInfo cmccDaUpChannelInfo = list.get(0);
                List<String> orderIdList = orderEntry.getValue().stream().map(CmccDaOrderInternalExportBO::getOrderId).collect(Collectors.toList());
                // 更新订单状态
                // TODO 待完成...
                //unOrderOperationService.refreshOrderList(orderIdList,cmccDaUpChannelInfo.getChannelId());
            }
        } catch (Exception e) {
            throw new ServiceException("导入表格出错");
        }
    }
}
